<script setup lang="ts">
import { computed } from 'vue';
import { NConfigProvider, darkTheme } from 'naive-ui';
import type { WatermarkProps } from 'naive-ui';
import { useAppStore } from './store/modules/app';
import { useThemeStore } from './store/modules/theme';
import { useAuthStore } from './store/modules/auth';
import { naiveDateLocales, naiveLocales } from './locales/naive';
import H5Router from './components/common/h5-router-new.vue';

defineOptions({
  name: 'App'
});

const appStore = useAppStore();
const themeStore = useThemeStore();
const authStore = useAuthStore();

const naiveDarkTheme = computed(() => (themeStore.darkMode ? darkTheme : undefined));

const naiveLocale = computed(() => {
  return naiveLocales[appStore.locale];
});

const naiveDateLocale = computed(() => {
  return naiveDateLocales[appStore.locale];
});

const watermarkProps = computed<WatermarkProps>(() => {
  const content =
    themeStore.watermark.enableUserName && authStore.userInfo.userName
      ? authStore.userInfo.userName
      : themeStore.watermark.text;

  return {
    content,
    cross: true,
    fullscreen: true,
    fontSize: 16,
    lineHeight: 16,
    width: 384,
    height: 384,
    xOffset: 12,
    yOffset: 60,
    rotate: -15,
    zIndex: 9999
  };
});

// H5Router事件处理
const handleH5RouterSuccess = (data?: any) => {
  appStore.setH5RouterSuccess();

  // 调用全局回调
  const callbacks = (window as any).__h5RouterCallbacks;
  if (callbacks?.onSuccess) {
    callbacks.onSuccess(data);
  }
};

const handleH5RouterClose = (hasChanges?: boolean) => {
  appStore.closeH5Router();

  // 调用全局回调
  const callbacks = (window as any).__h5RouterCallbacks;
  if (callbacks?.onClose) {
    callbacks.onClose(hasChanges);
  }

  // 清理回调函数
  (window as any).__h5RouterCallbacks = {};
};

const handleH5RouterError = (error?: any) => {
  // 调用全局回调
  const callbacks = (window as any).__h5RouterCallbacks;
  if (callbacks?.onError) {
    callbacks.onError(error);
  }
};
</script>

<template>
  <NConfigProvider
    :theme="naiveDarkTheme"
    :theme-overrides="themeStore.naiveTheme"
    :locale="naiveLocale"
    :date-locale="naiveDateLocale"
    class="h-full"
  >
    <AppProvider>
      <RouterView class="bg-layout" />
      <NWatermark v-if="themeStore.watermark.visible" v-bind="watermarkProps" />

      <!-- 全局H5Router组件 - 与原组件保持一致的调用方式 -->
      <H5Router />
    </AppProvider>
  </NConfigProvider>
</template>

<style scoped></style>
